package com.lifeservice.file.controller;

import com.lifeservice.common.core.controller.BaseController;
import com.lifeservice.common.core.domain.R;
import com.lifeservice.common.core.domain.UploadFile;
import com.lifeservice.file.service.ISysFileService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.text.DecimalFormat;

/**
 * 文件请求处理
 *
 * @author hoperun
 */
@RestController
@RequestMapping("/file")
public class SysFileController extends BaseController {
    private static final Logger log = LoggerFactory.getLogger(SysFileController.class);

    @Autowired
    private ISysFileService sysFileService;

    /**
     * 文件上传请求
     */
    @PostMapping("/upload")
    public R<UploadFile> upload(MultipartFile file, @RequestParam(defaultValue = "image") String tableName) {
        try {
            // 上传并返回访问地址
            UploadFile sysFile = sysFileService.uploadFile(file, tableName);

            sysFile.setSize(formatFileSize(file.getSize()));
            sysFile.setName(file.getOriginalFilename());

            return R.ok(sysFile);
        } catch (Exception e) {
            log.error("上传文件失败", e);
            return R.fail(e.getMessage());
        }
    }


    /**
     * 文件下载
     */
    @GetMapping("/download")
    public void download(HttpServletResponse response, @RequestParam(value = "url", required = false) String url) {
        if (StringUtils.isEmpty(url)) {
            return;
        }
        sysFileService.downloadFile(response, url);
    }

    public String formatFileSize(long fileS) {
        DecimalFormat df = new DecimalFormat("#.00");
        String fileSizeString;
        if (fileS < 1024) {
            fileSizeString = df.format((double) fileS) + "B";
        } else if (fileS < 1048576) {
            fileSizeString = df.format((double) fileS / 1024) + "KB";
        } else if (fileS < 1073741824) {
            fileSizeString = df.format((double) fileS / 1048576) + "M";
        } else {
            fileSizeString = df.format((double) fileS / 1073741824) + "GB";
        }
        return fileSizeString;
    }

}